/*
 * Project Name: jmax
 * File Name: OperationController.java
 * Copyright: Copyright(C) 1985-2015 ZKTeco Inc. All rights reserved.
 */
package com.xdtech.hotel.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.hotel.model.Device;
import com.xdtech.hotel.protocol.manager.DeviceMonitor;
import com.xdtech.hotel.protocol.manager.OperationManager;
import com.xdtech.hotel.protocol.manager.OperationOption;
import com.xdtech.hotel.protocol.util.ProtocolContants;
import com.xdtech.hotel.protocol.util.SocketClientUtils;
import com.xdtech.hotel.service.DeviceLinkOptionService;
import com.xdtech.hotel.service.DeviceLinkService;
import com.xdtech.hotel.service.DeviceService;
import com.xdtech.hotel.util.HotelConstants;
import com.xdtech.hotel.vo.DeviceItem;
import com.xdtech.hotel.vo.DeviceLinkItem;
import com.xdtech.hotel.vo.DeviceLinkOptionItem;
import com.xdtech.web.model.ResultMessage;

/**
 * 
 * @author max.zheng
 * @version TODO 添加版本
 * @see 相关类或方法，不需要请删除此行
 * @since 2015-4-9 上午11:31:24
 */
@Controller
@Scope("prototype")
public class DevOperationController
{
	@Autowired
	private DeviceService deviceService;
	@Autowired
	private DeviceLinkService deviceLinkService;
	@Autowired
	private DeviceLinkOptionService deviceLinkOptionService;
	@RequestMapping(value="/devOperation.do",params = "operationTest")
	public ModelAndView operationTest(HttpServletRequest request) {
		return new ModelAndView("hotel/device/operationTest_ftl");
	}
//	@RequestMapping(value="/devOperation.do",params = "operationMusic")
//	@ResponseBody
//	public ResultMessage operationMusic(int value,String sn) {
//		ResultMessage r = new ResultMessage();
//		OperationOption operationOption = OperationOption.createTvOrMusic(HotelConstants.COMPONENT_MUSIC, "0", "w", "on", value+"", "0");
//		OperationManager.operationComponent(sn,operationOption);
//		return r;
//	}
	/**
	 * 创建命令内容模版
	 * 
	 * @author max.zheng
	 * @create 2015-5-3上午11:27:36
	 * @modified by
	 * @param id
	 * @param type
	 * @return
	 */
	@RequestMapping(value="/devOperation.do",params = "getOperationTemp")
	@ResponseBody
	public ResultMessage getOperationTemp(Long id,String type) {
		DeviceItem deviceItem = deviceService.getDeviceItemById(id);
//		DeviceLinkItem deviceLinkItem = deviceLinkService.loadDeviceLinkItemByType(type);
//		List<DeviceLinkOptionItem> deviceLinkOptionItems = deviceLinkOptionService.loadDeviceLinkOptionsByLinkId(deviceLinkItem.getId());
//		JSONObject jsonObject = OperationManager.createCmdJson(deviceItem,deviceLinkItem,deviceLinkOptionItems);
		JSONObject jsonObject = OperationManager.createWrite(deviceItem.getSn(), type,null);
		ResultMessage rs = new ResultMessage();
		rs.setObj(jsonObject.toString());
		return rs;
	}
	/**
	 * 根据命令内容对应发送给设备
	 * 
	 * @author max.zheng
	 * @create 2015-5-3上午11:27:12
	 * @modified by
	 * @param id
	 * @param cmd
	 * @return
	 */
	@RequestMapping(value="/devOperation.do",params = "sendCmd")
	@ResponseBody
	public ResultMessage sendCmd(Long id,String cmd) {
		ResultMessage rs = new ResultMessage();
		DeviceItem deviceItem = deviceService.getDeviceItemById(id);
		if (DeviceMonitor.deviceIsOnline(deviceItem.getSn())) {
			String result = OperationManager.sendData(deviceItem.getSn(),deviceItem.getIp(), Integer.valueOf(deviceItem.getPort()), cmd);
			setCmdResult(rs, result);
		}else {
			rs.setSuccess(false);
			rs.setMsg(ProtocolContants.MSG_OFFLINE);
		}
		return rs;
	}
	/**
	 * 创建读取命令内容
	 * 
	 * @author max.zheng
	 * @create 2015-5-3上午11:28:23
	 * @modified by
	 * @param id
	 * @param type
	 * @return
	 */
	@RequestMapping(value="/devOperation.do",params = "getOperationStatus")
	@ResponseBody
	public ResultMessage getOperationStatus(Long id,String type) {
		DeviceItem deviceItem = deviceService.getDeviceItemById(id);
		JSONObject jsonObject = OperationManager.createRead(deviceItem.getSn(), type);
		ResultMessage rs = new ResultMessage();
		rs.setObj(jsonObject.toString());
		return rs;
	}
	/**
	 * 发送状态信息读取内容命令
	 * 
	 * @author max.zheng
	 * @create 2015-5-3上午11:28:39
	 * @modified by
	 * @param id
	 * @param cmd
	 * @return
	 */
	@RequestMapping(value="/devOperation.do",params = "sendReadStatusCmd")
	@ResponseBody
	public ResultMessage sendReadStatusCmd(Long id,String cmd) {
		ResultMessage rs = new ResultMessage();
		DeviceItem deviceItem = deviceService.getDeviceItemById(id);
		if (DeviceMonitor.deviceIsOnline(deviceItem.getSn())) {
			String result = OperationManager.sendData(deviceItem.getSn(),deviceItem.getIp(), Integer.valueOf(deviceItem.getPort()), cmd);
			setCmdResult(rs, result);
		}else {
			rs.setSuccess(false);
			rs.setMsg(ProtocolContants.MSG_OFFLINE);
			rs.setObj(ProtocolContants.MSG_OFFLINE);
		}
		return rs;
	}
	/**
	 * 
	 * @author max.zheng
	 * @create 2015-6-4下午11:26:36
	 * @modified by
	 * @param rs
	 * @param result
	 */
	private void setCmdResult(ResultMessage rs, String result) {
		boolean rb = false;
		if (result!=null&&result.contains("true")) {
			rb = true;
			rs.setMsg("操作成功");
		}
		else
		{
			rb = true;
			rs.setMsg("设备返回值有误:"+result);
		}
		if (!rb) {
			rs.setMsg("设备通信失败，请检查网络，或查看设备监控，确认设备是否正常通信.");
		}
	}
	
	/**
	 * 发送写命令
	 * 
	 * @author max.zheng
	 * @create 2015-5-3上午11:29:39
	 * @modified by
	 * @param id
	 * @param cmd
	 * @return
	 */
	@RequestMapping(value="/devOperation.do",params = "sendWriteCmd")
	@ResponseBody
	public ResultMessage sendWriteCmd(Long id,String type,String cmdData) {
		ResultMessage rs = new ResultMessage();
		DeviceItem deviceItem = deviceService.getDeviceItemById(id);
		//判断是否在线
		if (DeviceMonitor.deviceIsOnline(deviceItem.getSn())) {
			JSONObject jsonObject = OperationManager.createWrite(deviceItem.getSn(), type,cmdData);
			String result = OperationManager.sendData(deviceItem.getSn(),deviceItem.getIp(), Integer.valueOf(deviceItem.getPort()), jsonObject.toString());
			setCmdResult(rs, result);
		}else {
			rs.setSuccess(false);
			rs.setMsg("RCU主控设备处于离线状态，无法通讯，请检查网络.");
		}
		return rs;
	}
	
	@RequestMapping(value="/devOperation.do",params = "syncDeviceTime")
	@ResponseBody
	public ResultMessage syncDeviceTime(String sns) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(sns)) {
			String[] tempSns = sns.split(",");
			StringBuffer checkStr = new StringBuffer();
			for (String sn : tempSns) {
				if (!DeviceMonitor.deviceIsOnline(sn)) {
					checkStr.append("设备"+sn+"处于离线状态，无法操作\r\n");
				}
			}
			
			if (checkStr.length()>0) {
				r.setSuccess(false);
				r.setMsg(checkStr.toString());
			}else {
				//验证通过,同步设备时间操作
				for (String sn : tempSns) {
					if(!OperationManager.sendWriteCmdToDev(sn, HotelConstants.DEV_TIME_CONTROL, null)) {
						//假如一个设备同步失败
						checkStr.append("设备"+sn+"同步失败\r\n");
					}
				}
				//暂未处理设备命令执行失败情况
				if (checkStr.length()>0) {
					r.setSuccess(false);
					r.setMsg(checkStr.toString());
				}
			}
		}else {
			r.setSuccess(false);
		}
		return r;
	}
}
